package dnspod

import (
	"net/url"
	"strconv"

	"github.com/antonholmquist/jason"
)

// Domain domain
type Domain struct {
	ID        int
	Name      string
	Status    string
	ExtStatus string
	Records   int
}

func getDomain(obj *jason.Object) Domain {
	id := getID(obj)
	name, err := obj.GetString("name")
	assert(err)
	status, err := obj.GetString("status")
	assert(err)
	extStatus, err := obj.GetString("ext_status")
	assert(err)
	records, err := obj.GetString("records")
	var nrecords int64
	if err != nil {
		switch err.(type) {
		case jason.KeyNotFoundError:
			// optional key
		default:
			panic(err)
		}
	} else {
		nrecords, err = strconv.ParseInt(records, 10, 64)
		assert(err)
	}
	return Domain{
		ID:        int(id),
		Name:      name,
		Status:    status,
		ExtStatus: extStatus,
		Records:   int(nrecords),
	}
}

// DomainList list all domains
func (c Client) DomainList(keyword string) ([]Domain, error) {
	params := make(url.Values)
	params.Set("type", "all")
	if len(keyword) > 0 {
		params.Set("keyword", keyword)
	}
	var ret []Domain
	err := c.list("Domain.List", params, func(obj *jason.Object) (int, bool) {
		code, err := obj.GetString("status", "code")
		assert(err)
		if code == "9" { // no domains
			return 0, false
		}
		// status
		checkResponseCode(obj, "Domain.List", true)

		// parse domains
		domains, err := obj.GetObjectArray("domains")
		assert(err)
		var cnt int
		for _, domain := range domains {
			ret = append(ret, getDomain(domain))
			cnt++
		}

		// want next
		all, err := obj.GetInt64("info", "all_total")
		assert(err)
		if len(ret) >= int(all) {
			return cnt, false
		}
		return cnt, true
	})
	if err != nil {
		return nil, err
	}
	return ret, nil
}
